<?php
class CustomUrlRule extends CBaseUrlRule {

    public $rules;

    public function createUrl($manager, $route, $params, $ampersand) {
        
        $patterns=array_search($route, $this->rules);
        if($patterns===FALSE) return false; // this rule does not apply
        $patterns = array_filter(explode('/',$patterns));

        $routePattern = $pair = array();
        foreach ($patterns as $key => $pattern) {
            $tr = array();
            if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) {
                $bol = true;
                foreach ($matches[1] as $key => $value) {
                    if (!isset($params[$value]))
                        $bol = false;
                }
                if (!$bol)
                    continue;

                $tokens = array_combine($matches[1], $matches[2]);
                foreach ($tokens as $name => $value) {
                    if (isset($params[$name])) {
                        if (empty($value))
                            $tr['<' . $name . '>'] = $params[$name];
                        else {
                            $tr['<' . $name . ':' . $value . '>'] = $params[$name];
                        }
                        unset($params[$name]);
                    }
                }//end foreach
            } else {
                $routePattern[]=$pattern;
                continue;
            }//end if			

            if (!empty($tr)) {
                $routePattern[] = strtr($pattern, $tr);
            }//end new			
        }//end foreach

        $url = implode('/', array_filter($routePattern));
        foreach ($params as $key => $value) {
            $pair[] = $key . '=' . $value;
        }

        if (count($pair)) {
            $url .= '?' . implode('&', $pair);
        }
        return $url;
        
        /*
          if ($route==='car/index')
          {
          if (isset($params['test'], $params['test2']))
          return $params['test'] . '/' . $params['test2'];
          else if (isset($params['test']))
          return $params['test'];
          } */
    }

    public function parseUrl($manager, $request, $pathInfo, $rawPathInfo) {
        /*
          $str = 'foobar: 2008';
          //preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

          preg_match('/(?P<name>[^\/]+): (?P<digit>[^\/]+)/', $str, $matches);
          print_r($matches);
          echo '<br /><br />';

          $str = 'corporate-456-abc-sdn-bhd-28';
          preg_match('/corporate-(?P<abc>\d+)-(?P<name>[^\/]+)-(?P<digit>[^\/]+)/', $str, $matches);
          print_r($matches);
          echo '<br /><br />';
         */

        if ($pathInfo === '')
            return;

        $pathInfo.='/';
        $route = $patterns = '';

        foreach ($this->rules as $pattern => $value) {
            $i=0;
            $keywords = array_filter(preg_split("/<(\w+):?(.*?)?>/", $pattern));
            foreach($keywords as $keyword){
                $pos = strripos($pathInfo, $keyword);
                if($pos !== false) $i++;
            }
            if($i){
                $route=$value;
                $patterns=array_filter(explode('/',$pattern)); 
                break;
            }//end if
        }//end foreach
        
        if (empty($route)) return false;  // this rule does not apply
                
        $segs = array_filter(explode('/', $pathInfo));
        foreach ($segs as $segment) {
            foreach ($patterns as $name => $pattern) {

                $tr2['/'] = $tr['/'] = '\\/';
                if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) {
                    $tokens = array_combine($matches[1], $matches[2]);
                    foreach ($tokens as $name => $value) {
                        if ($value === '') {
                            $value = '[^\/]+';
                            $tr['<' . $name . '>'] = "(?P<$name>$value)";
                        } else {
                            $tr['<' . $name . ':' . $value . '>'] = "(?P<$name>$value)";
                        }
                        if (isset($references[$name]))
                            $tr2["<$name>"] = $tr["<$name>"];
                        else
                            $params[$name] = $value;
                    }//end foreach
                }//end if

                $rulesPattern = '/^' . strtr($pattern, $tr) . '/';
                if (preg_match($rulesPattern, $segment, $matches)) {
                    foreach ($matches as $key => $value) {
                        if (isset($references[$key]))
                            $tr[$references[$key]] = $value;
                        else if (isset($params[$key]))
                            $_REQUEST[$key] = $_GET[$key] = $value;
                    }//end foreach
                    break;
                }else {
                    continue;
                }//end if else
            }//end foreach
        }//end foreach
        return $route;
        
        /* 		
          if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches))
          {
          // check $matches[1] and $matches[3] to see
          // if they match a manufacturer and a model in the database
          // If so, set $_GET['manufacturer'] and/or $_GET['model']
          // and return 'car/index'
          }
          return false;  // this rule does not apply
         */
    }//end function
}//end class